/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-08 15:07:43
 * Copyright (c) 2015- joysuch-版权所有
 */
package com.joysuch.wwyt.bp.repository;

import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Set;


/**
 * BpContractorDao
 */
public interface BpContractorDao extends JpaRepository<BpContractor, Long>, JpaSpecificationExecutor<BpContractor> {

    @Query(value = "update BpContractor b set b.state= 0 where b.id=:id")
    @Modifying
    void nullify(Long id);

    @Query("select b from BpContractor b where b.state=1 and b.dutyScriptRemindOrNot=0 and b.dutyScriptExpireDate is not null")
    List<BpContractor> findRemindTask();

    @Query("select b from BpContractor b where b.state=1")
    List<BpContractor> findAllContractor();

    @Query(value = "select count(*) from wwyt_bp_contractor  where delete_flag = '0' and state=1 and company_name=?1", nativeQuery = true)
    int countByName(String companyName);

    @Query(value = "select * from wwyt_bp_contractor b where b.code =?1 and  b.state=1 and b.org_code like ?2% limit 1 ", nativeQuery = true)
    BpContractor findByCodeAndCompanyCode(String code, String companyName);

    @Query(value = "select * from wwyt_bp_contractor b where  state=1 and delete_flag='0' and org_code like ?1% ", nativeQuery = true)
    List<BpContractor> findAllContractorByCompanyCode(String companyCode);

    @Query(value = "select id from wwyt_bp_contractor b where  state=1 and delete_flag='0' and company_name like %?1% ", nativeQuery = true)
    List<Long> findIdsByName(String companyName);

    @Query(value = "select * from wwyt_bp_contractor b where b.contractor_type=:contractorType and if(:nameOrCode !='' && :nameOrCode is not null,(b.company_name like %:nameOrCode%  or b.CODE like %:nameOrCode% ),1=1) and b.state=1 and b.delete_flag='0'", nativeQuery = true)
    Page<BpContractor> findSimplePage(String nameOrCode, String contractorType, Pageable page);

    @Query(value = "SELECT `NAME` FROM wwyt_bp_depart  WHERE ID = ?1 and delete_flag='0' and (show_state IS NULL OR show_state!=44) ", nativeQuery = true)
    String selectResponsibleDeptName(Long ResponsibleDept);

    @Query(value = "SELECT ID FROM wwyt_bp_contractor WHERE responsible_dept in ?1 and delete_flag='0' ", nativeQuery = true)
    Set<Long> findAllContractorIdsByDepartIds(Set<Long> authDepartIdsByCurUser);

    @Query(value = "select count(*) from wwyt_bp_contractor  where delete_flag = '0' and state=1 and company_name=?1 and id!=?2", nativeQuery = true)
    int countByNameAndIdNotEq(String companyName, Long id);
}
